<template>
  <div>
    <!-- 工单信息 -->
    <BreakSpace label="工单信息"></BreakSpace>
    <FormPanel ref="orderPanel" :list="orderList" labelWidth="100" formType="show"></FormPanel>
    <!-- 车辆信息 -->
    <BreakSpace label="车辆信息"></BreakSpace>
    <FormPanel ref="vehiclePanel" :list="vehicleList" labelWidth="100" formType="show"></FormPanel>
    <!-- 结算单信息 -->
    <BreakSpace label="结算单信息"></BreakSpace>
    <FormPanel ref="balancePanel" :list="balanceList" labelWidth="100" formType="show"></FormPanel>
    <el-tabs v-model="defaultTabLabel">
      <el-tab-pane name="1" label="维修项目" lazy>
        <repairProject :dataSource="projectDataSource" :rowData="rowData" :roNo="rowData.roNo" :allUser="allUser" :chargePartition="chargePartition" />
      </el-tab-pane>
      <el-tab-pane name="2" label="维修材料" lazy>
        <repairStuff :dataSource="stuffDataSource" :rowData="rowData" :roNo="rowData.roNo" :allUser="allUser" :chargePartition="chargePartition" />
      </el-tab-pane>
      <el-tab-pane name="3" label="附件项目" lazy>
        <additionalProject :dataSource="additionalDataSource" :rowData="rowData" :roNo="rowData.roNo" :allUser="allUser" :chargePartition="chargePartition" />
      </el-tab-pane>
    </el-tabs>
    <!-- 费用信息 -->
    <BreakSpace label="费用信息"></BreakSpace>
    <FormPanel ref="feePanel" :list="feeList" labelWidth="100" formType="show"></FormPanel>
    <!-- 优惠金额 -->
    <el-tabs v-model="defaultDiscountTab">
      <el-tab-pane name="1" label="优惠金额" lazy>
        <FilterTable :columns="ticketColumns" :dataSource="ticketDataSource" :onColumnsChange="columns => (this.ticketColumns = columns)">
          <template slot="controls" slot-scope="props"> </template>
        </FilterTable>
      </el-tab-pane>
    </el-tabs>
    <!-- 应收实收 -->
    <el-tabs v-model="defaultReceiveTab">
      <el-tab-pane name="1" label="应收" lazy>
        <FilterTable :columns="receivableColumns" height="200" :dataSource="receivableDataSource" :onColumnsChange="columns => (this.receivableColumns = columns)">
          <template slot="controls" slot-scope="props"> </template>
        </FilterTable>
      </el-tab-pane>
      <el-tab-pane name="2" label="实收" lazy>
        <FilterTable :columns="receiptsColumns" height="200" :dataSource="receiptsDataSource" :onColumnsChange="columns => (this.receiptsColumns = columns)">
          <template slot="controls" slot-scope="props"> </template>
        </FilterTable>
      </el-tab-pane>
    </el-tabs>
    <div
      :style="{
        position: 'absolute',
        left: 0,
        bottom: 0,
        right: 0,
        zIndex: 9,
        borderTop: '1px solid #e9e9e9',
        padding: '10px 20px',
        background: '#fff',
        textAlign: 'right'
      }"
    >
      <ButtonArea align="right">
        <printRepairOrder :roNo="rowData.roNo" :ownerCode="rowData.ownerCode" />
        <printBalanceOrder :roNo="rowData.roNo" :ownerCode="rowData.ownerCode" btnText="打印结算单" />

        <el-button @click="closeDialog">取 消</el-button>
      </ButtonArea>
    </div>
  </div>
</template>
<script>
import { dictionary } from '@/utils/dictMixin';
import moment from 'moment';
import repairProject from './tabs/repairProject';
import repairStuff from './tabs/repairStuff';
import additionalProject from './tabs/additionalProject';
import printRepairOrder from '@/pages/repair/repairManage/repairQuery/printRepairOrder_oem';
import printBalanceOrder from '@/pages/repair/repairManage/repairQuery/printBalanceOrder_oem';
import { searchRepairOrderDetailOem, getRepairTypes } from '@/api/repair/repairManage/repairFeeQuery/index.js';
import { getSystemDefault } from '@/api/repair/common';
import { getNameByIds } from '@/api/repair/common/index.js';

export default {
  name: 'OrderPanel',
  components: { repairProject, repairStuff, additionalProject, printRepairOrder, printBalanceOrder },
  mixins: [dictionary],
  props: {
    rowData: {
      type: Object,
      default: () => ({})
    },
    allUser: {
      type: Array,
      default: () => []
    },
    chargePartition: {
      type: Array,
      default: () => []
    }
  },
  data() {
    return {
      orderList: this.createOrderList(),
      vehicleList: this.createVehicleList(),
      balanceList: this.createBalanceList(),
      feeList: this.createFeeList(),
      ticketColumns: this.createTicketColumns(),
      receivableColumns: this.createReceivableColumns(),
      receiptsColumns: this.createReceiptsColumns(),
      projectDataSource: [],
      stuffDataSource: [],
      additionalDataSource: [],
      ticketDataSource: [],
      receivableDataSource: [],
      receiptsDataSource: [],
      defaultTabLabel: '1',
      defaultDiscountTab: '1',
      defaultReceiveTab: '1',
      tax: 0.13
    };
  },
  created() {
    this.searchRepairOrderDetailOem();
    this.queryTaxRate();
    this.getRepairTypesFun();
  },
  methods: {
    // 获取维修类型
    async getRepairTypesFun() {
      const res = await getRepairTypes();
      this.repairList = res.data.map(x => ({ value: x.REPAIR_TYPE_CODE, text: x.REPAIR_TYPE_NAME }));
      this.orderList.find(x => x.fieldName === 'repairTypeCode').itemList = this.repairList;
    },
    // 查询税率
    async queryTaxRate() {
      let res = await getSystemDefault({ itemCode: 1003 });
      if (res.resultCode == 200) {
        this.tax = res.data;
        console.log(res.data, 'queryTaxRate');
      }
    },
    async searchRepairOrderDetailOem() {
      let res = await searchRepairOrderDetailOem({ ownerCode: this.rowData.ownerCode, roNo: this.rowData.roNo, balanceNo: this.rowData.balanceNo });
      if (res.resultCode == 200) {
        console.log(res.data, 'searchRepairOrderDetailOem');
        let dataSource = res.data;

        this.orderList.forEach(x => {
          x.initialValue = dataSource[x.fieldName];
        });
        // 翻译服务顾问
        if (dataSource.serviceAdvisor && dataSource.serviceAdvisor.length) {
          let res = await getNameByIds({ userIds: dataSource.serviceAdvisor });
          if (res.resultCode == 200) {
            let userList = res.data.map(x => ({ text: x.employeeName, value: x.employeeId + '' }));
            this.orderList.find(x => x.fieldName === 'serviceAdvisor').itemList = userList;
          }
        }
        this.vehicleList.forEach(x => {
          x.initialValue = dataSource[x.fieldName];
        });
        this.balanceList.forEach(x => {
          x.initialValue = dataSource[x.fieldName];
        });
        this.feeList.forEach(x => {
          if (x.fieldName === 'payTypeCode') {
            x.initialValue = Number(dataSource[x.fieldName]);
            return;
          }
          x.initialValue = dataSource[x.fieldName];
        });

        this.projectDataSource = [...dataSource.labourList];
        this.stuffDataSource = [...dataSource.partList];
        this.additionalDataSource = [...dataSource.addLabourList];
        this.receivableDataSource = [...dataSource.balanceObjList];
        this.receiptsDataSource = [...dataSource.balanceObjList];
        // this.ticketDataSource =
        let fee = {
          sumAmount: 0, // 汇总金额
          realTotalAmount: 0,
          taxAmount: 0, // 税额：不含税金额*税率；
          netAmount: 0, // 不含税金额：实收总金额
          discountAmount: 0, // 合计优惠金额：使用优惠券或者打折后的合计，
          subObbAmount: 0 // 去零金额：
        };

        // if(dataSource.labourList && dataSource.labourList.length) {
        //   dataSource.labourList.forEach(x=>{
        //     fee.sumAmount += x.labourAmount;
        //     fee.realTotalAmount += x.receiveAmount;
        //     fee.taxAmount += x.receiveAmount;

        //   })
        // }
        // if(dataSource.partList && dataSource.partList.length) {
        //   dataSource.partList.forEach(x=>{
        //     fee.sumAmount += x.partSalesAmount;
        //   })
        // }
        // if(dataSource.addLabourList && dataSource.addLabourList.length) {
        //   dataSource.addLabourList.forEach(x=>{
        //     fee.sumAmount += x.addItemAmount;
        //     fee.realTotalAmount += x.receiveAmount
        //   })
        // }

        // if (dataSource.balanceObjList && dataSource.balanceObjList.length) {
        //   dataSource.balanceObjList.forEach(x => {
        //     fee.sumAmount += x.sumAmount;
        //     fee.realTotalAmount += x.realTotalAmount;
        //     fee.taxAmount += x.taxAmount;
        //     fee.netAmount += x.netAmount;
        //     fee.subObbAmount += x.subObbAmount;
        //   });
        // }
        // // 合计优惠金额：使用优惠券或者打折后的合计，
        // fee.discountAmount += fee.taxAmount; // TODO:加上优惠券金额+ ;

        // this.feeList.find(x => x.fieldName === 'sumAmount').initialValue = fee.sumAmount.toFixed(2);
        // this.feeList.find(x => x.fieldName === 'realTotalAmount').initialValue = (fee.realTotalAmount + fee.subObbAmount).toFixed(2);
        // this.feeList.find(x => x.fieldName === 'tax').initialValue = this.tax || '0.13';
        // this.feeList.find(x => x.fieldName === 'taxAmount').initialValue = fee.taxAmount.toFixed(2);
        // this.feeList.find(x => x.fieldName === 'netAmount').initialValue = fee.netAmount.toFixed(2);
        // this.feeList.find(x => x.fieldName === 'subObbAmount').initialValue = fee.subObbAmount.toFixed(2);
        // this.feeList.find(x => x.fieldName === 'discountAmount').initialValue = fee.discountAmount.toFixed(2);
        // this.feeList.find(x => x.fieldName === 'totalAmount').initialValue = fee.realTotalAmount.toFixed(2); // 合计优化 // 自费总金额

        // 设置经销商名称-后台不返，从前一级页面传入
        this.orderList.find(x => x.fieldName === 'ownerShortName').initialValue = this.rowData.ownerShortName;
      }
    },
    createOrderList() {
      return [
        {
          type: 'INPUT',
          label: '经销商代码',
          fieldName: 'ownerCode',
          initialValue: ''
        },
        {
          type: 'INPUT',
          label: '经销商名称',
          fieldName: 'ownerShortName',
          placeholder: '请选择...',
          initialValue: '',
          readonly: true,
          unitRender: () => {
            return (
              <el-button
                icon="el-icon-search"
                onClick={() => {
                  this.dealerAction = { type: '', visible: true, title: '选择经销商', data: {} };
                }}
              ></el-button>
            );
          }
        },
        {
          type: 'INPUT',
          label: '工单号',
          fieldName: 'roNo',
          placeholder: '请输入...'
        },
        {
          type: 'SELECT',
          label: '维修类型',
          fieldName: 'repairTypeCode',
          placeholder: '请选择',
          itemList: []
        },
        {
          type: 'SELECT',
          label: '服务顾问',
          fieldName: 'serviceAdvisor',
          itemList: []
        },
        {
          type: 'DATE',
          label: '开单日期',
          fieldName: 'roCreateDate'
        },
        {
          type: 'SELECT',
          label: '希望联系方式',
          fieldName: 'delivererHobbyContact',
          itemList: this.createDictList(1012),
          placeholder: ''
        },
        {
          type: 'SELECT',
          label: '电访时间',
          fieldName: 'traceTime',
          itemList: this.createDictList(8029),
          placeholder: ''
        },
        {
          type: 'INPUT',
          label: '行驶里程',
          fieldName: 'inMileage'
        },
        {
          type: 'INPUT',
          label: '检查结果',
          fieldName: 'checkResult',
          selfCols: 2
        }
      ];
    },
    createVehicleList() {
      return [
        {
          type: 'INPUT',
          label: '车牌号',
          fieldName: 'license'
        },
        {
          type: 'INPUT',
          label: 'VIN',
          fieldName: 'vin'
        },
        {
          type: 'INPUT',
          label: '车主',
          fieldName: 'ownerName'
        },
        {
          type: 'INPUT',
          label: '送修人姓名',
          fieldName: 'deliverer'
        },
        {
          type: 'INPUT',
          label: '品牌',
          fieldName: 'brandName'
        },
        {
          type: 'INPUT',
          label: '车系',
          fieldName: 'seriesName'
        },
        {
          type: 'INPUT',
          label: '车型',
          fieldName: 'modelName'
        }
      ];
    },
    createBalanceList() {
      return [
        {
          type: 'INPUT',
          label: '结算单号',
          fieldName: 'balanceNo'
        },
        {
          type: 'INPUT',
          label: '结算单备注',
          fieldName: 'remark'
        }
      ];
    },
    createFeeList() {
      return [
        {
          type: 'SELECT',
          label: '优惠模式',
          fieldName: 'discountModeName',
          placeholder: '',
          filterable: true,
          itemList: []
        },
        {
          type: 'SELECT',
          label: '付款方式',
          fieldName: 'payTypeCode',
          placeholder: '请选择',
          itemList: this.createDictList('8044'),
          rules: [{ required: false, message: '请选择付款方式', trigger: 'change' }]
        },
        {
          type: 'CHECKBOX',
          label: '是否欠款结算',
          fieldName: 'arrBalance',
          options: {
            trueValue: 10041001,
            falseValue: 10041002
          }
        },

        {
          type: 'INPUT',
          label: '汇总金额',
          fieldName: 'sumAmount',
          initialValue: ''
        },
        {
          type: 'INPUT',
          label: '实收总金额',
          fieldName: 'realReceiveAmount',
          initialValue: ''
        },
        {
          type: 'INPUT',
          label: '税率',
          fieldName: 'tax'
        },
        {
          type: 'INPUT',
          label: '税额',
          fieldName: 'taxAmount'
        },
        {
          type: 'INPUT',
          label: '不含税金额',
          fieldName: 'netAmount'
        },

        {
          type: 'INPUT',
          label: '去零金额',
          fieldName: 'subObbAmount'
        },
        {
          type: 'INPUT',
          label: '合计优惠金额',
          fieldName: 'totalDiscountAmount',
          initialValue: ''
        },
        {
          type: 'INPUT',
          label: '自费总金额',
          fieldName: 'receiveAmount'
        },
        {
          type: 'INPUT',
          label: '索赔成本',
          fieldName: 'claimCost',
          initialValue: ''
        }
      ];
    },
    // 点击保存按钮触发的事件，参数是表单数据对象
    formchangeFun(val) {
      this.saveData = val;
    },
    // 优惠券
    createTicketColumns() {
      return [
        {
          title: '序号',
          dataIndex: 'index',
          width: 80,
          sorter: true,
          render: (props, h) => {
            return <span>{props.row.index + 1}</span>;
          }
        },
        {
          title: '操作',
          dataIndex: 'operation',
          render: (props, h) => {
            return (
              <div>
                <el-button type="text">同步</el-button>
                <el-button type="text">删除</el-button>
              </div>
            );
          }
        },
        {
          title: '优惠券代码',
          dataIndex: 'code',
          sorter: true
        },
        {
          title: '优惠券名称',
          dataIndex: 'name',
          sorter: true
        },
        {
          title: '优惠券类型',
          dataIndex: 'type',
          sorter: true
        },
        {
          title: '优惠金额',
          dataIndex: 'amount',
          sorter: true
        },
        {
          title: '是否已使用',
          dataIndex: 'used',
          sorter: true
        }
      ];
    },
    createReceivableColumns() {
      return [
        {
          title: '序号',
          dataIndex: 'index',
          width: 80,
          sorter: true,
          render: (props, h) => {
            return <span>{props.row.index + 1}</span>;
          }
        },
        {
          title: '收费对象代码',
          dataIndex: 'paymentObjectCode'
        },
        {
          title: '收费对象名称',
          dataIndex: 'paymentObjectName',
          showOverflowTooltip: true
        },
        {
          title: '应收工时费',
          dataIndex: 'receiveableLabourFee',
          precision: 2
        },
        {
          title: '应收维修材料费',
          dataIndex: 'receiveableRepairPartFee',
          precision: 2
        },
        // {
        //   title: '应收销售材料费',
        //   dataIndex: 'RECEIVEABLE_SALES_PART_FEE',
        //   sorter: true,
        //   filter: true,
        //   filterType: 'number',
        //   precision: 2
        // },
        {
          title: '应收附加项目费',
          dataIndex: 'receiveableAddItemFee',
          precision: 2
        },
        {
          title: '应收总金额',
          dataIndex: 'CALC_RECEIVEABLE_TOTAL_AMOUNT',
          precision: 2,
          render: props => {
            let total = props.row.receiveableLabourFee + props.row.receiveableRepairPartFee + props.row.receiveableAddItemFee;
            return <span>{total}</span>;
          }
        }
      ];
    },
    createReceiptsColumns() {
      return [
        {
          title: '序号',
          dataIndex: 'index',
          width: 80,
          sorter: true,
          render: (props, h) => {
            return <span>{props.row.index + 1}</span>;
          }
        },
        {
          title: '收费对象代码',
          dataIndex: 'paymentObjectCode'
        },
        {
          title: '收费对象名称',
          dataIndex: 'paymentObjectName',
          showOverflowTooltip: true
        },
        {
          title: '实收工时费',
          dataIndex: 'realLabourFee',
          precision: 2
        },
        {
          title: '实收维修材料费',
          dataIndex: 'realRepairPartFee',

          precision: 2
        },
        // {
        //   title: '实收销售材料费',
        //   dataIndex: 'REAL_SALES_PART_FEE',
        //   sorter: true,
        //   filter: true,
        //   filterType: 'input',
        //   precision: 2
        // },
        {
          title: '实收附加项目费',
          dataIndex: 'realAddItemFee',
          precision: 2
        },
        {
          title: '汇总金额',
          dataIndex: 'sumAmount',
          precision: 2
        },
        {
          title: '实收总金额',
          dataIndex: 'realTotalAmount',
          precision: 2
        },
        {
          title: '税额',
          dataIndex: 'taxAmount',
          precision: 2
        },
        {
          title: '不含税金额',
          dataIndex: 'netAmount',
          precision: 2
        },
        {
          title: '去零金额',
          dataIndex: 'subObbAmount',
          precision: 2
        },
        {
          title: '应收账款',
          dataIndex: 'receivableAmount',
          precision: 2
        },
        {
          title: '已收账款',
          dataIndex: 'receivedAmount',
          width: 150,
          precision: 2
        },
        {
          title: '未收账款',
          dataIndex: 'notReceivedAmount',
          precision: 2
        },
        {
          title: '是否结清',
          dataIndex: 'payOff',
          dictItems: this.createDictList('1004')
        },
        {
          title: '已开票',
          dataIndex: 'invoiceTag',
          dictItems: this.createDictList('1004')
        }
      ];
    },

    closeDialog() {
      this.$emit('closeDialog', false);
    },
    printPayOrder() {},
    printOrder() {}
  }
};
</script>

<style lang="less" scoped></style>
